<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="/WEB-INF/tlds/spring.tld"%>
<%@ taglib prefix="c" uri="/WEB-INF/tlds/c.tld"%>
<c:set var="BasePath" value="${pageContext.request.contextPath}"></c:set>
<c:set var="Plugins" value="${pageContext.request.contextPath}/res/plugins"></c:set>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>新增采购单</title>
<link href="${Plugins}/ligerUI/skins/Aqua/css/ligerui-all.css" rel="stylesheet" type="text/css" />
<link href="${Plugins}/ligerUI/skins/ligerui-icons.css" rel="stylesheet" type="text/css" />
<script src="${Plugins}/jquery/jquery-1.3.2.min.js"	type="text/javascript"></script>
<script src="${Plugins}/ligerUI/js/ligerui.min.js" type="text/javascript"></script>
<script src="${Plugins}/jquery-validation/jquery.validate.min.js" type="text/javascript"></script>
<script src="${Plugins}/jquery-validation/jquery.metadata.js" type="text/javascript"></script>
<script src="${Plugins}/jquery-validation/messages_cn.js" type="text/javascript"></script>
<script src="${BasePath}/res/js/common/jquery.form.js" type="text/javascript"></script>
<script src="${BasePath}/res/js/common/jquery.validate.method.js" type="text/javascript"></script>
<script type="text/javascript" src="${BasePath}/res/js/ligerCommon.js"></script>
<script src="${Plugins}/datepicker/WdatePicker.js" type="text/javascript"></script>
<script type="text/javascript" src="${BasePath}/res/js/json2.js"></script>

<style type="text/css">
    body{ font-size:12px;}
    .l-table-edit {}
    .l-table-edit-td{ padding:4px;}
    .l-button-submit,.l-button-test{width:80px; float:left; margin-left:10px; padding-bottom:2px;}
    .l-verify-tip{ left:230px; top:120px;}
    .navbar {
		height: 20px;
		border-bottom: #E6E6E6 solid 1px;
		line-height: 20px;
	}
	.p-tab .s-lab{font-size:12px;font-family:"微软雅黑",​"宋体",​Arial,​sans-serif;}
	input.l-textarea{width:170px;height:20px;font-size:12px;float:left;}
</style>
</head>
<body style="padding:10px">
<div class="navbar">
		<span>您当前的位置：</span>
		采购管理 &gt; 采购单管理 &gt; 新增采购单
</div>
<form name="form1" method="post" action="add_purchase.do" id="form1">
	<!-- 封装采购单总价格，在页面提供val()方法计算叠加 -->
	<input type="hidden" id="totalPrice" name="totalPrice" />
   <table  cellpadding="0" cellspacing="0" class="l-table-edit p-tab" >
    <tr>
        <td align="right" class="l-table-edit-td s-lab"><font  color="red">*</font>采购单名称：</td>
        <td align="left" width="100%" class="l-table-edit-td "><input name="poName" type="text" id="poName" value="${prv.poName }" class="l-textarea" maxlength="50" validate="{required:true,rangelength:[1,50]}" /></td>
        <td align="left"></td>
    </tr>
      <tr>
       <td align="right" width="100px;"  class="l-table-edit-td s-lab"><font  color="red">*</font>预计采购日期：</td>
       <td align="left" class="l-table-edit-td "> 
       <input id="auditTime" type="text" name="foPurDate" readonly="readonly" value="${prv.foPurDate }" class="Wdate l-textarea" value="" size="21"
    	onFocus="WdatePicker({dateFmt:'yyyy-MM-dd',readOnly:true,autoPickDate:true,minDate:'%y-%M-{%d+1}'})" validate="{required:true,rangelength:[10,18]}" /> 
       </td><td align="left"></td>
     </tr>  
    <tr>
      <td align="right" class="l-table-edit-td s-lab"><font  color="red">*</font>供应商名称：</td>
        <td align="left" width="100%" class="l-table-edit-td s-lab">
        <input name="supName" id="supName" value="${prv.supName }" class="l-textarea" maxlength="50" validate="{required:true,rangelength:[1,50]}" />
        <input name="supCode" type="hidden" id="supId" value="${prv.supCode }">
        <input type="button" value="选择供应商" id="elect_purSupper" class="l-button l-button-test" />
        </td>
        <td align="left"> </td>
    </tr>
    <td>
    
    </td>
 
    <tr>
        <td align="right" class="l-table-edit-td s-lab" >采购单类型：</td>
        <td align="left" class="l-table-edit-td "> 
    		<select style="z-index: -999;font-size: 12px;" id="purcType" name="purcType" class="l-textarea">
				<option value="1">产品采购</option>
				<option value="2">样品采购</option>
				<option value="3">其他采购</option>
			</select>
		</td>
		<td align="left"></td>
    </tr>
    
     <tr>
        <td align="right" class="l-table-edit-td s-lab">
        	<input type="button" value="选择商品" id="elect_product" class="l-button l-button-test" />
        </td>
        <td align="left" class="l-table-edit-td ">
        	<input type="hidden" id="productlist" name="productlist" />
        </td>
        <td align="left"></td>
     </tr>
      <tr id="xzProductList" style="display: none;">
     <tr>
        <td colspan="3" align="left" class="l-table-edit-td s-lab">
        <div id="maingrid" style="margin:0; padding:0"></div>
		  <div style="display:none;">
		  <!-- 展示列表数据  -->
		</div>
		</td>
     </tr>
     <tr>
        <td align="right" class="l-table-edit-td s-lab"><font  color="red">*</font>采购描述：</td>
        <td align="left" class="l-table-edit-td"></td>
        <td align="left"></td>
     </tr>
     <tr>
        <td colspan="3" align="left" class="l-table-edit-td">
        	<textarea title="请输入采购描述" class="l-textarea" rows="5" cols="120" name="prDescribe" validate="{required:true,rangelength:[1,2000]}" ></textarea>
        </td>
     </tr>
</table>


<input type="submit" value="确定" id="submit1" class="l-button l-button-submit" /> 
<input type="button" value="取消" name="tests" id="tests" class="l-button l-button-test" />
</form>
</body>
<script>

var basePath ="${BasePath}";
//供应商编码
var scode ="";
//供应商名称
var sname="";
//成本价格
var actprice="";
/* function showPoDetail(poNo, num) {
	var title = num == 1 ? "修改采购单":"采购单详情";
	window.parent.f_addTab(new Date().getTime(), title, '../../../manager/purchase/orders/showPoDetail.do?poNo=' + poNo + '&num=' + num);
} */

$(document).ready(function(){
	//选择商品子窗口
	$("#elect_product").click(function(){
		list = new Array();
	   	var m =$.ligerDialog.open({
	   				title:'请购商品',
	   				url:'${BasePath}/manager/purchase/orders/getCommodityList.do?code='+scode,
	   				height:500,width:700,
	   				buttons: [{ text: '确定', onclick: function (item, dialog) { 
	   									dialog.frame.valProd();
	   									if(!dialog.frame.isOut) return false;
	   									addProduct(); 
	   									dialog.close(); 
	   								} 
	   						  },
	   				          { text: '取消', onclick: function (item, dialog) { dialog.close(); list = new Array();} } ],
	   				isResize: false, 
	   				isDrag: false 
	   		});
	   	m.show(); 
	});
	
	addProduct();
//选择供应商
	//选择商品子窗口
	$("#elect_purSupper").click(function(){
		//getSupplyInfo();
		list = new Array();
	   	var m =$.ligerDialog.open({
	   				title:'请购供应商',
	   				url:'${BasePath}/manager/purchase/orders/getSupplierInfoList.do',
	   				height:500,width:700,
	   				buttons: [{ text: '确定', onclick: function (item, dialog) { 
	   					
	   									/* alert(JSON.stringify($("#elect_purSupper").getData())); */
	   									//$('#supName').val('2132');
	   									//addProduct(); 
	   									$("#supName").val(sname);
  		            					$("#supId").val(scode);
	   									dialog.close(); 
	   								} 
	   						  },
	   				          { text: '取消', onclick: function (item, dialog) { dialog.close(); list = new Array();} } ],
	   				isResize: false, 
	   				isDrag: false 
	   		});
	   	m.show();
	});
	
});

//仓库
var hw = ${house};
var hwData = [];
$.each(hw,function(){
	hwData.push({"purWhNo": this["whNo"],"text": this["whName"]});
});

//查询
var sel = "";
//临时请购商品集合
var list = new Array();
//请购商品集合
var commoditylist = new Array();
//格式化日期
function FormatDate (strTime) {
    var date = new Date(strTime);
    return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
}

//请购商品列表
function addProduct(){
	commoditylist = commoditylist.concat(list);
	//$.ligerDialog.warn(JSON.stringify(commoditylist));
	commodityData = {"Rows": commoditylist, "Total": commoditylist.length};
	grid = $("#maingrid").ligerGrid({
        columns: [
        { display: '货品编号', name: 'prodNo'},
        { display: '商品名称', name: 'commoName'},
        { display: '货品条码', name: 'prodBarCode'},
        { display: '箱包装规格', name: 'casePakgSize'},
        { display: '出厂日期', name: 'manufactureTime',type: "date", format: 'yyyy-MM-dd', width: 100,editor: { type: "date"},
        	 render:function(rowdata, rowindex, value){
        		 if( value == undefined){
 					return value = '请输入时间';	
 				}else{
 					 rowdata.manufactureTime = commoditylist[rowindex].manufactureTime = value;
 				}
        		 return FormatDate(rowdata.manufactureTime);
        	} 
        },
       /*  { display: '保质截止日期', name: 'shelfLife',type: "date", format: 'yyyy-MM-dd', width: 100,editor: { type: "date"},
       	 render:function(rowdata, rowindex, value){
       		 if( value == undefined){
					return value = '请输入时间';	
				}else{
					 rowdata.shelfLife = commoditylist[rowindex].shelfLife = value;
				}
       		 return FormatDate(rowdata.shelfLife);
       	} 
       }, */
         { display: '保质期天数', name: 'shelfLife',type: 'int', width: 100,editor: { type: 'int',maxValue:999999999,minValue:1},
        	render:function(rowdata, rowindex, value){
				if(value == null || value < 0){
					value = '请输入天数';	
				}else{
					return rowdata.shelfLife = commoditylist[rowindex].shelfLife = value;
				}
				return rowdata.shelfLife = commoditylist[rowindex].shelfLife = value;
        	}
        },  
        { display: '零售价', name: 'salePrice',type:'float',editor: { type: 'float',maxValue:999999999,minValue:0},
        	render:function(rowdata, rowindex, value){
				if(value == undefined || value == 0)value = '0';
        		return rowdata.salePrice = commoditylist[rowindex].salePrice = value;
        	}
        },
       /*  { display: '是否可退货', name: 'isReturnedGoos' ,render: function (rowdata, rowindex, value) {
        	if (value == 0) {
        		return '可退货';
        	} else if (value == 1) {
        		return '不可退货';
        	}   else {
        		return '状态不明';
        	}
        }}, */
        /* { display: '供应商',width:300,columns:[
				{ display: '选择', render:function(rowdata, rowindex, value){
					var t = "<a href='javascript: getSupplyInfo(\""+rowdata.prodNo+"\",\""+rowindex+"\");' >选择供应商</a>";
					return t;
				}},
        		{ display: '供应商名称', name: 'purSuppName'},
        		{ display: '成本价', name: 'actprice',type:'float',editor: { type: 'float',maxValue:999999999,minValue:0},
        			render:function(rowdata, rowindex, value){
        				if(value == undefined || value == 0)value = '0';
                		return rowdata.actprice = commoditylist[rowindex].actprice = value;
                	}
        		}]
        }, */
        
        /* { display: '成本价', name: 'ppUnitPrice',editor:{type:'float'}}, */
         { display: '成本价', name: 'ppUnitPrice',type:'float',editor: { type: 'float',maxValue:999999999,minValue:0},
			render:function(rowdata, rowindex, value){
				if(value == undefined || value == 0)value = '0';
        		return rowdata.ppUnitPrice = commoditylist[rowindex].ppUnitPrice = value;
        	}
		}, 
        { display: '最低订货数量', name: 'buyNum'},
        
        
        { display: '数量', name: 'ppNumber',type:'int',editor: { type: 'int',maxValue:999999999,minValue:1},
        	render:function(rowdata, rowindex, value){
        		var n = "<font style='color: blue;font-size: 12px;'>请输入数量</font>";
        		ppNumber = rowdata.ppNumber > 0 ? rowdata.ppNumber : 0;
        		if(value > 0 && ppNumber <= value){
        			value = parseInt(value,10);
        			n = rowdata.ppNumber = commoditylist[rowindex].ppNumber = value;
        		}else{
        			commoditylist[rowindex].ppNumber = rowdata.ppNumber = 0;
        		}
        		return n;
        	}
        },
        
        { display: '仓库' , name: 'purWhName', width: 150,editor: { type: 'select', data: hwData, valueField: 'purWhNo'},
        	render:function(rowdata, rowindex, value){
        		var n = "";
        		if(value != null){
        			for ( var i = 0; i < hwData.length; i++) {
    					if(value == hwData[i].purWhNo){
    						commoditylist[rowindex].purWhNo = value;
    						n = commoditylist[rowindex].purWhName = hwData[i].text;
    					}
    				}
        			if(n == ''){
        				n = value;
        			}
        		}
        		if(n == ''){
        			n = "<font style='color: blue;font-size: 12px;'>请选择仓库</font>";
        		}
        		return n;
        	}	
        },
    	{ display: '采购总价',name:"totalPrice",
        	render:function(rowdata, rowindex, value){
        		if(rowdata.ppNumber != null && rowdata.ppUnitPrice != null){
        			var p = rowdata.ppNumber * rowdata.ppUnitPrice;
            		var num = new Number(p);
            		value = num.toFixed(2);
            		commoditylist[rowindex].totalPrice = value;
        		}
        		if(value == null || value == "") value ="0.00";
        		return value;
        	}	
    	},
        { display: '操作', isSort: false, render: function (rowdata, rowindex, value){
           	var  text = "<input type='button' value='删除' onclick='removeThis("+rowindex+");' />";
            return text;
        	}
        }
        ], 
        width: '100%',
        height: '330',
        usePager: false,enabledEdit: true,
        data: $.extend(true,{},commodityData)
    });
	list = new Array();
}

//删除商品
function removeThis(o) {
	commoditylist.splice(o,1);
	addProduct();
}



//选择供应商
function getSupplyInfo(prodNo,index){
	scode = sname= actprice="";
	//var cid=grid.getData()[index].prodNo;
  	  m=$.ligerDialog.open({title:'选择供应商',
  		 url:"${BasePath}/manager/purchase/orders/pageFinderSupplier.do?prodNo='"+prodNo+"'",height:400,width:800,isResize: false,
  		 isDrag: false,
  		 buttons: [ 
  		            { text: '确定', onclick: function (item, dialog) {
  		            		getActprice(prodNo);
  		            		//commoditylist[index].actprice = actprice;
  		            		//commoditylist[index].purSuppNo = scode;
  		            		//commoditylist[index].purSuppName = sname;
  		            		$("#supName").val(sname);
  		            		$("#supId").val(scode);
  		            		dialog.close();
  		            		//addProduct();
  		            	} 
  		            }, 
  		            { text: '取消', onclick: function (item, dialog) { dialog.close(); } }] 
  		 });
  	
  	 m.show(); 
}

//货品促销成本
function getActprice(prodNo){
	var url = '${BasePath}/purchase/getAjaxPromotionsCost.do';
	$.post(url,{prodNo:prodNo},function(data){
		if(data != null && data != -1){
			actprice = data;
		}
	});
}


//货品列表数据验证
var prod = true;
function valData() {
	prod = true;
	var header = {'ppNumber': '数量','ppUnitPrice': '供应商','purWhNo': '仓库'};
	
	//出厂日期
	 $.each(commoditylist,function(index,item){
			if(item.manufactureTime == undefined){
				$.ligerDialog.warn("出厂日期不能为空!");
				prod = false;
				return false;
			}
			if(!prod) return prod;
		}); 
	
	//保质截止日期
	 $.each(commoditylist,function(index,item){
			if(item.shelfLife == undefined){
				$.ligerDialog.warn("保质截止日期不能为空!");
				prod = false;
				return false;
			}
			if(!prod) return prod;
		});
	
	//商品
	if(commoditylist.length < 1){
		$.ligerDialog.warn("请添加商品!");
		prod = false;
		return false;
	}
	
	$.each(commoditylist,function(index,item){
		$.each(commoditylist,function(i,t){
			if(item.prodNo == t.prodNo && index != i){
				$.ligerDialog.warn("货品" +item['prodNo']+"有重复添加!");
				prod = false;
				return false;
			}
		});
		if(!prod)return prod;
	});
	
	//成本价
	 $.each(commoditylist,function(index,item){
		if(item.ppUnitPrice == 0){
			$.ligerDialog.warn("货品成本价不能为空!");
			prod = false;
			return false;
		}
		
	
		if(!prod) return prod;
	}); 
	 
	//采购数量
	 $.each(commoditylist,function(index,item){
			if(item.ppNumber == 0){
				$.ligerDialog.warn("采购数量不能为空!");
				prod = false;
				return false;
			}else if(item.ppNumber < item.buyNum ){
				$.ligerDialog.warn("采购数量不能少于最低订货数量!");
				prod = false;
				return false;
			}
		
			if(!prod) return prod;
		}); 
	 
	//仓库
	 $.each(commoditylist,function(index,item){
			if(item.purWhNo == null){
				$.ligerDialog.warn("货品仓库不能为空!");
				prod = false;
				
				return false;
			}
			
		
			if(!prod) return prod;
		}); 
	 
	//货品总价格
	 var poTotalPrice=0;
	 $.each(commoditylist,function(index,item){
			if(item.totalPrice == null){
				$.ligerDialog.warn("货品总价不能为空!");
				prod = false;
				return false;
			}else{
				poTotalPrice = (poTotalPrice*1+item.totalPrice*1).toFixed(2);
    		}
			if(!prod) return prod;
		}); 
	 $("#totalPrice").val(poTotalPrice);
	$("#productlist").val(JSON.stringify(commoditylist));
}


//from提交
$(function ()
		{
			//validate
		    $.metadata.setType("attr", "validate");
		    var v = $("form").validate({
		        errorPlacement: function (lable, element)
		        {
		        	lable.ligerHideTip();
		            if (element.hasClass("l-textarea"))
		            {
		                element.ligerTip({ content: lable.html(), target: element[0] }); 
		            }
		            else if (element.hasClass("l-text-field"))
		            {
		                element.parent().ligerTip({ content: lable.html(), target: element[0] });
		            }
		            else
		            {
		                lable.appendTo(element.parents("td:first").next("td"));
		            }
		            
		        },
		        submitHandler:function()
		        {
		        	$("form .l-text,.l-textarea").ligerHideTip();
		        	valData();
		        	if(!prod) return prod;
		            var options = {
		            		type: 'POST',
		            		beforeSend: function(){
		            			$("#form1").find(":submit,:button").attr("disabled", true);
		            		},
		            		success: function(data){
		            			if(data=="success") {
		            				window.parent.f_tip('新增成功');
		            				close_liger_tab();
		            			}else if(data == "wharefail"){
		            				window.parent.f_tip('(虚实)仓库不匹配请重新选择仓库!');
		            				$("#form1").find(":submit,:button").attr("disabled", false);
		            			}else if(data == 'failRepeat'){
		            				window.parent.f_tip('采购单重复请再退出重新添加!');
		            			} else {
		            				window.parent.f_tip('新增失败');
		            			}
		            		}
		            	}, $form1 = $("#form1");
		           $form1.ajaxSubmit(options);
		           return false;
		        }
		    });
}); 
// 取消
$("#tests").click(function() {
	close_liger_tab();
});	
</script>
</html>